package com.pmt.feedplayer.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.pmt.feedplayer.data.VideoItem
import com.pmt.feedplayer.data.VideoListState
import platform.Foundation.*
import platform.UIKit.*
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap

/**
 * 视频列表组件 - iOS平台实现
 */
@Composable
actual fun VideoFeed(
    videos: VideoListState,
    onVideoClick: (VideoItem) -> Unit,
    onLoadMore: () -> Unit
) {
    Column(modifier = Modifier.fillMaxSize()) {
        when (videos) {
            is VideoListState.Loading -> {
                // 显示骨架图列表
                LazyColumn(modifier = Modifier.fillMaxSize()) {
                    items(5) { _ ->
                        VideoItemSkeleton()
                    }
                }
            }
            is VideoListState.Success -> {
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(16.dp)
                ) {
                    items(videos.data) { video ->
                        VideoItem(
                        video = video,
                        onClick = { onVideoClick(video) }
                    )
                    }
                    
                    // 添加加载更多项 - Material 3 风格
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            Row(
                                modifier = Modifier
                                    .background(
                                        color = MaterialTheme.colorScheme.surfaceVariant,
                                        shape = MaterialTheme.shapes.medium
                                    )
                                    .padding(12.dp)
                                    .clickable(onClick = onLoadMore),
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.Center
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(20.dp),
                                    strokeWidth = 2.dp,
                                    color = MaterialTheme.colorScheme.primary
                                )
                                Text(
                                    text = "加载更多...",
                                    modifier = Modifier.padding(start = 12.dp),
                                    style = MaterialTheme.typography.bodyMedium,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }
                    }
                }
            }
            is VideoListState.Error -> {
                Column(
                    modifier = Modifier.fillMaxSize(),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    // 错误状态简单占位
                    Spacer(modifier = Modifier.height(20.dp))
                }
            }
        }
    }
}

/**
 * iOS平台的图片加载组件
 */
@Composable
fun UIImageView(filePath: String, modifier: Modifier = Modifier) {
    var image by remember { mutableStateOf<ImageBitmap?>(null) }
    var isLoading by remember { mutableStateOf(true) }
    
    // 加载图片
    Box(modifier = modifier) {
        // 显示加载指示器
        if (isLoading) {
            CircularProgressIndicator(
                modifier = Modifier.align(Alignment.Center),
                color = MaterialTheme.colorScheme.primary
            )
        }
        
        // 图片加载完成后显示
        image?.let {\ bitmap ->
            androidx.compose.foundation.Image(
                bitmap = bitmap,
                contentDescription = "Video thumbnail",
                contentScale = ContentScale.Crop,
                modifier = Modifier.fillMaxSize()
            )
        }
        
        // 开始加载图片
        DisposableEffect(filePath) {
            isLoading = true
            
            // 在后台线程加载图片
            NSThread.detachNewThread { ->
                try {
                    val image = UIImage.imageWithContentsOfFile(filePath)
                    image?.let {\ uiImage ->
                        val cgImage = uiImage.CGImage
                        cgImage?.let {\ cg ->
                            // 切换到主线程更新UI
                            dispatch_async(dispatch_get_main_queue()) {
                                image = cg.asImageBitmap()
                                isLoading = false
                            }
                        }
                    } ?: run {
                        // 图片加载失败
                        dispatch_async(dispatch_get_main_queue()) {
                            isLoading = false
                        }
                    }
                } catch (e: Exception) {
                    println("Error loading image: $e")
                    dispatch_async(dispatch_get_main_queue()) {
                        isLoading = false
                    }
                }
            }
            
            onDispose {}
        }
    }
}

/**
 * 格式化视频时长
 */
fun formatDuration(milliseconds: Long): String {
    val totalSeconds = milliseconds / 1000
    val minutes = totalSeconds / 60
    val seconds = totalSeconds % 60
    return String.format("%02d:%02d", minutes, seconds)
}

/**
 * 单个视频项组件 - iOS平台实现
 */
@Composable
actual fun VideoItem(video: VideoItem, onClick: () -> Unit) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 16.dp)
            .clickable(onClick = onClick)
    ) {
        // 视频缩略图区域
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
                .background(Color.Gray)
        ) {
            // 显示视频缩略图
            if (video.thumbnailUrl.isNotEmpty()) {
                UIImageView(
                    filePath = video.thumbnailUrl,
                    modifier = Modifier.fillMaxSize()
                )
            } else {
                // 缩略图未加载或不存在时显示占位
                Box(
                    modifier = Modifier.fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "加载中...",
                        color = Color.White,
                        style = MaterialTheme.typography.bodyMedium
                    )
                }
            }
            
            // 视频图标
            Box(
                modifier = Modifier
                    .size(48.dp)
                    .align(Alignment.Center)
                    .background(Color.Black.copy(alpha = 0.5f))
            ) {
                // 简单的播放图标占位
                Text(
                    text = "▶",
                    color = Color.White,
                    fontSize = 24.sp,
                    modifier = Modifier.align(Alignment.Center)
                )
            }
            
            // 时长标签
            Box(
                modifier = Modifier
                    .align(Alignment.BottomEnd)
                    .background(Color.Black.copy(alpha = 0.7f))
                    .padding(4.dp)
                    .padding(horizontal = 8.dp)
            ) {
                Text(
                    text = formatDuration(video.duration),
                    color = Color.White,
                    fontSize = 12.sp
                )
            }
        }
        
        // 视频信息
        Column(modifier = Modifier.padding(12.dp)) {
            Text(
                text = video.title,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(bottom = 8.dp),
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            
            // 作者信息
            Text(
                text = video.authorName ?: "未知作者",
                color = Color.Gray,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                fontSize = 12.sp
            )
        }
    }
}

/**
 * 视频项骨架图组件
 */
@Composable
private fun VideoItemSkeleton() {
    Column(modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp)) {
        // 缩略图骨架
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
                .background(Color.LightGray)
        )
        
        // 视频信息骨架
        Column(modifier = Modifier.padding(12.dp)) {
            // 标题骨架
            Box(
                modifier = Modifier
                    .fillMaxWidth(0.8f)
                    .height(20.dp)
                    .padding(bottom = 8.dp)
                    .background(Color.LightGray)
            )
            
            // 作者信息骨架
            Box(
                modifier = Modifier
                    .fillMaxWidth(0.6f)
                    .height(16.dp)
                    .background(Color.LightGray)
            )
        }
    }
}